package com.sunmnet.j2ee.service.powerdb.designer.impl;

import com.sunmnet.j2ee.core.pub.QueryFilter;
import com.sunmnet.j2ee.core.pub.init.PKInit;
import com.sunmnet.j2ee.core.pub.sqlloader.SqlLoader;
import com.sunmnet.j2ee.dao.BaseDao;
import com.sunmnet.j2ee.entity.powerdb.designer.DbConnInfo;
import com.sunmnet.j2ee.service.impl.BaseServiceImpl;
import com.sunmnet.j2ee.service.powerdb.designer.DbConnInfoService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 蔡岳衡 on 2016/7/28.
 */
@Repository("/powerdb/designer/dbConnInfoService")
public class DbConnInfoServiceImpl extends BaseServiceImpl<DbConnInfo, Long> implements DbConnInfoService {

    /**
     * log4j2日志 *
     */
    private static final Logger LOG = LogManager.getLogger(DbConnInfoServiceImpl.class.getName());


    private static final String CLASS_NAME = DbConnInfoServiceImpl.class.getName();

    private static final String SQL_SAVE_DB_RELATE_ACC =
            SqlLoader.getInstance().getSql(CLASS_NAME, "SQL_SAVE_DB_RELATE_ACC");

    private static final String SQL_DELETE_DB_RELATE_ACC =
            SqlLoader.getInstance().getSql(CLASS_NAME, "SQL_DELETE_DB_RELATE_ACC");

    private static final String SQL_SELECT_DB_RELATE_ACC =
            SqlLoader.getInstance().getSql(CLASS_NAME, "SQL_SELECT_DB_RELATE_ACC");

    private static final String SQL_SELECT_DB_CONN_INFO =
            SqlLoader.getInstance().getSql(CLASS_NAME, "SQL_SELECT_DB_CONN_INFO");

    private static final String SQL_UPDATE_DB_CONN_INFO =
            SqlLoader.getInstance().getSql(CLASS_NAME, "SQL_UPDATE_DB_CONN_INFO");

    private static final String SQL_UPDATE_DB_CONN_INFO_PASSWORD =
            SqlLoader.getInstance().getSql(CLASS_NAME, "SQL_UPDATE_DB_CONN_INFO_PASSWORD");

    private static final String FIND_SQL_FOR_SAVE = "from DbConnInfo t where upper(t.name)=upper(:name)";
    private static final String FIND_SQL_FOR_UPDATE = "from DbConnInfo t where upper(t.name)=upper(:name) and t.id!=:id";


    @Resource(name = "/powerdb/designer/dbConnInfoDao")
    @Override
    public void setDao(BaseDao<DbConnInfo, Long> dao) {
        super.dao = dao;
    }

    @Override
    public int checkRepeat(DbConnInfo dbConnInfo) {

        Map params = new HashMap();
        params.put("name", dbConnInfo.getName());

        String sql = FIND_SQL_FOR_SAVE;
        if (dbConnInfo.getId() != null) {
            sql = FIND_SQL_FOR_UPDATE;
            params.put("id", dbConnInfo.getId());
        }

        List list = dao.find(sql, params);
        if (list != null && list.size() > 0) {
            LOG.debug("数据库连接" + dbConnInfo.getName() + "已经存在");
            return 1;
        }
        return 0;
    }

    @Override
    public List getDbRelAccount(long dbId) throws Exception {

        List result;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("dbId", dbId);

        try {
            result = dao.findBySql(SQL_SELECT_DB_RELATE_ACC, params);
        } catch (Exception e) {
            throw new Exception("查询失败" + e.getMessage(), e);
        }
        return result;
    }

    @Override
    public short saveDbRelateAccount(long dbId, String accountIds) throws Exception {

        if (accountIds == null) {
            throw new Exception("账户列表为空");
        }

        int result = 0;
        String[] accountIdList = accountIds.split(",");

        try {
            for (String accountId : accountIdList) {
                Map<String, Object> saveParams = new HashMap<String, Object>();
                saveParams.put("id", PKInit.pk.getID());
                saveParams.put("dbId", dbId);
                saveParams.put("accountId", Long.valueOf(accountId));

                result = dao.executeSql(SQL_SAVE_DB_RELATE_ACC, saveParams);
            }
        } catch (Exception e) {
            throw new Exception("插入失败" + e.getMessage(), e);
        }
        return (short) result;
    }

    @Override
    public short deleteDbRelateAccount(long dbId, String accountIds) throws Exception {

		/*//log4j配置打印日志的级别
                //启动的变量
				LOG.debug(SQL_DELETE_DB_RELATE_ACC);
				//代码执行过程
				LOG.info("");
				//参数没有配置
				LOG.warn("");
				//异常 打印错误堆栈
				LOG.error("");*/

        if (accountIds == null) {
            throw new Exception("账户列表为空");
        }

        int result = 0;
        Map<String, Object> deleteParams = new HashMap<String, Object>();
        try {
            deleteParams.put("dbId", dbId);
            String sql = SQL_DELETE_DB_RELATE_ACC.replace(":accountIds", accountIds);

            result = dao.executeSql(sql, deleteParams);
        } catch (Exception e) {
            throw new Exception("删除失败" + e.getMessage(), e);
        }
        return (short) result;
    }

    @Override
    public List<Map<String, Object>> getDbConnInfo(QueryFilter filter) {
        filter.setSql(SQL_SELECT_DB_CONN_INFO);
        String sql = filter.createSql();
        return dao.findBySql(sql);
    }

    @Override
    public int updateDbConnInfo(DbConnInfo dbConnInfo) {
        Map params = new HashMap();
        params.put("name", dbConnInfo.getName());
        params.put("dbName", dbConnInfo.getDbName());
        params.put("modifyAccountId", dbConnInfo.getModifyAccountId());
        params.put("ip", dbConnInfo.getIp());
        params.put("url", dbConnInfo.getUrl());
        params.put("port", dbConnInfo.getPort());
        params.put("status", dbConnInfo.getStatus());
        params.put("type", dbConnInfo.getType());
        params.put("charset", dbConnInfo.getCharset());
        params.put("modifyTime", new Date());
        params.put("remark", dbConnInfo.getRemark());
        params.put("id", dbConnInfo.getId());

        return dao.executeSql(SQL_UPDATE_DB_CONN_INFO, params);
    }

    @Override
    public int updatePassword(long id, String password) {
        Map params = new HashMap();
        params.put("password", password);
        params.put("id", id);

        return dao.executeSql(SQL_UPDATE_DB_CONN_INFO_PASSWORD, params);
    }
}
